#include "dbtabtabversion.h"
#include "databasequery.h"
#include "dbtabtabversion.h"

const QLatin1String DBTabTabVersion::TAB_NAME = QLatin1String("tab_ver");
const char *DBTabTabVersion::_TAB_NAME = "name";
const char *DBTabTabVersion::_TAB_VER  = "version";

const DBTabTabVersion::ColumnInfo DBTabTabVersion::mColumnTab[]=
{
    [INDEX_ID]       = {DBTabTabVersion::_ID,          "integer primary key AUTOINCREMENT"},
    [INDEX_TAB_NAME] = {DBTabTabVersion::_TAB_NAME,    "key vchar"},
    [INDEX_TAB_VER]  = {DBTabTabVersion::_TAB_VER,     "int "},
    [INDEX_END]      = {nullptr,nullptr},
};

DBTabTabVersion::DBTabTabVersion():DBTabBase(QLatin1String(TAB_NAME))
{

}

void DBTabTabVersion::createTab(QSqlDatabase &db)
{
    DBTabBase::createTab(mTabName,mColumnTab,db);
}


void DBTabTabVersion::setVersion(const QString &tab_name,int version, QSqlDatabase &db)
{
    DataBaseQuery query(db);
    QMap<QString,QVariant> map;
    map.insert(_TAB_NAME,tab_name);
    map.insert(_TAB_VER,version);

    query.selectTable(TAB_NAME,NULL,QString(_TAB_NAME)+"='" + tab_name+"'");


    if(query.first()){
        query.updateItem(TAB_NAME,_TAB_NAME,tab_name,map);
    }else{
        query.insert(TAB_NAME,map);
    }
}

int DBTabTabVersion::getVersion(const QString &name,QSqlDatabase &db)
{
    DataBaseQuery query(db);
    query.selectTable(TAB_NAME,NULL,QString(_TAB_NAME)+"='" + name+"'");


    if(query.first())
    {
        return query.value(INDEX_TAB_VER).toInt();
    }
    return 0;
}


void DBTabTabVersion::incVersion(const QString &tab_name,QSqlDatabase &db)
{
    int i = DBTabTabVersion::getVersion(tab_name,db);
    i++;

    DBTabTabVersion::setVersion(tab_name,i,db);
}




